<?php
class tpb {
    private $url;
    private $html;
    private $categories;
    
    public function __construct() {
        $this->setUrl($null);
        $this->setHtml();
        $this->setCategories();
    }
    
    private function setUrl($url) {
        try {
            //Supplied Url?
            if(isset($url)) {
                $this->url = $url;
                return true;
            }
            //Go to config for Url
            $config = new config();
            $config->section = "tpb";
            $config->value = "url";
            $url = $config->getConfig();
            if(count($url) != 1) {
                throw new Exception("Error getting url from config file");
            }
            $this->url = $url;
            return true;
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
    
    private function setHtml() {
        try {
            //Get the Url page source
            if(!$html = file_get_contents($this->url)) {
                throw new Exception("Cannot get url content");
            }
            $this->html = $html;
            return true;
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
    
    private function setCategories() {
        try {
            $doc = new DOMDocument();
            //Dismiss any warnings over html
            if(!@$doc->loadHTML($this->html)) {
                throw new Exception("Unable to load html");
            }
            //Extract the category list
            $select = $doc->getElementById("category");
            if($select == null) {
                throw new Exception("Unable to find categories list");
            }
            //Loop through options
            $categories = $select->getElementsByTagName("option");
            if($categories->item(0) == null) {
                throw new Exception("Unable to find categories in list");
            }
            foreach($categories as $category) {
                $value = $category->getAttribute("value");
                if($value == "") {
                    throw new Exception("Unable to find category node attribute");
                }
                $text = $category->nodeValue;
                if($text == "") {
                    throw new Exception("Unable to get category node value");
                }
                $this->categories[$value] = $text;
            }
            //Sort categories
            if(count($this->categories) > 0) {
                if(!asort($this->categories)) {
                    throw new Exception("Unable to sort categories");
                }
            }
            else {
                throw new Exception("No categories found");
            }
            return true;
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
    
    public function getCategoriesSelectList() {
        try {
            //Ensure we've got categories
            if(count($this->categories) == 0) {
                throw new Exception("Unable to load select list");
            }
            //Script to process option change
            echo '<script language="javascript" src="script/doSelectOnChange.js"></script>';
            //Loop through categories generating list
            echo '<select id="category" name="category" onChange="doSelectOnChange(this.value)">';
            foreach($this->categories as $key => $value) {
                //Decide if we already have one selected
                if($_GET["cat"] == $key) {
                    echo '<option value="'. $key .'" selected>'. $value .'</option>';
                    continue;
                }
                echo '<option value="'. $key .'">'. $value .'</option>';
            }
            echo "</select>";
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
    
    public function getSearchResultsTable($cat) {
        try {
            //Ensure we have a valid category
            if(!$this->isCategoryInList($cat)) {
                throw new Exception("Unknown category selected");
            }
            //Get the results
            $results = $this->getSearchResults($cat);
            //print_r($results);
            //Format the results into a table
            echo "<table>";
            foreach($results as $result) {
                echo "<tr>";
                echo '<td><a href="'. $result["href"] .'">'. $result["text"] ."</a></td>";
                echo "<td>". $result["date"] ."</td>";
                echo "<td>". $result["size"] ."</td>";
                echo "</tr>";
            }
            echo "</table>";
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
    
    private function getSearchResults($cat) {
        try {
            //Update the html page
            $url = $this->url ."/". $cat;
            $this->url = $url;
            $this->setHtml();
            //Extract the results table
            $doc = new DOMDocument();
            //Dismiss any warnings over html
            if(!@$doc->loadHTML($this->html)) {
                throw new Exception("Unable to load html");
            }
            //Extract the table
            $table = $doc->getElementById("searchResult");
            if($table == null) {
                throw new Exception("Unable to find result table");
            }
            //Loop through rows
            $rows = $table->getElementsByTagName("tr");
            if($rows->item(0) == null) {
                throw new Exception("Unable to find rows in result table");
            }
            foreach($rows as $row) {
                //Loop through the columns
                $cols = $row->getElementsByTagName("td");
                foreach($cols as $col) {
                    //Loop through the links
                    unset($text);
                    $links = $col->getElementsByTagName("a");
                    foreach($links as $link) {
                        //Get text
                        if(!isset($text)) {
                            $class = $link->getAttribute("class");
                            if($class != "detLink") {
                                continue;
                            }
                            $text = $link->nodeValue;
                        }
                        //Get href
                        $href = $link->getAttribute("href");
                        if(strstr($href, "magnet:?")) {
                            break;
                        }
                    }
                    //Disguard rows that are empty
                    if(!isset($text)) {
                        continue;
                    }
                    //Get the font tag
                    $font = $col->getElementsByTagName("font")->item(0)->nodeValue;
                    if(strlen($font) == 0) {
//                        throw new Exception("Unable to find row font text");
                    }
                    //Get elements from text
                    $explode = explode(" ", str_replace(",", "", $font));
                    //Replace word days with date
                    $date = $explode[1];
                    $today = date_create();
                    //TODO - BUG - Date add not working
                    //$date = str_replace("Today", $today->format("m-d"), $date);
                    //$date = str_replace("Y-day", $today->add(new DateInterval("d1"))->format("m-d"), $date);
                    //TODO - Replace silly size ids
                    $size = $explode[3];
                    //Add striped row to new array
                    $results[] = array("text" => $text, "href" => $href, "date" => $date, "size" => $size);
                }
            }
            return $results;
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
    
    private function isCategoryInList($cat) {
        try {
            //Do we have what we need?
            if(isset($cat)) {
                //Does the category exist?
                if(array_key_exists($cat, $this->categories)) {
                    return true;
                }
            }
            return false;
        }
        catch(Exception $e) {
            throw new customException($e);
        }
    }
}
?>